package com.grm.distributed.lock.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * redisson-信号量semaphore，分布式（类比于juc中的Semaphore，单机版）
 *
 * 限制一定数量的线程能够去执行（限流等操作）
 */
@Service
@Slf4j
public class ProductService14 {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 信号量-限制一定数量的线程能够去执行
     */
    public void testSemaphore(Integer id) {
        RSemaphore semaphore = this.redissonClient.getSemaphore("semaphore");
        // 限制同时执行数5
        semaphore.trySetPermits(5);
        try {
            semaphore.acquire();
            this.redisTemplate.opsForList()
                .rightPush("log", "id=" + id + ",获取了资源，开始处理逻辑。" + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(10 + new Random().nextInt(10));
            this.redisTemplate.opsForList()
                .rightPush("log", "id=" + id + ",处理完逻辑，释放资源。" + Thread.currentThread().getName());
            semaphore.release();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
